package com.ccp.dev.system.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.dao.GlobalTypeDao;
import com.ccp.dev.system.dao.SysTypeKeyDao;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysTypeKey;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * GlobalType service类
 *
 * @author caishaofan
 */
@Service
public class GlobalTypeService extends BaseService<GlobalType> {

    @Resource
    private GlobalTypeDao globalTypeDao;

    @Resource
    private SysTypeKeyDao sysTypeKeyDao;

    /**
     * 设置类型默认为树型数据
     */
    private static final String TREE_TYPE_LAYUI="1";

    /**
     * 根据catkey获取数据。
     *
     * @param catKey 分类key
     * @return List<GlobalType> 集合
     */
    public List<GlobalType> getByCatKey(String catKey, boolean hasRoot,String treeType) {

        String tenantId = ContextUtil.getCurrentUserTenantId();
        List<GlobalType> list = globalTypeDao.getByCatKey(catKey, tenantId,treeType);

        //是否有根节点
        if (hasRoot) {
            SysTypeKey sysTypeKey = sysTypeKeyDao.getSysTypeKeyByKey(catKey);
            GlobalType globalType = new GlobalType();
            globalType.setTypeName(sysTypeKey.getTypeName());
            globalType.setCatKey(sysTypeKey.getTypeKey());
            //todo 参数单独定义
            globalType.setParentId("0");
            globalType.setIsParent("true");
            globalType.setTypeId(sysTypeKey.getTypeId());
            globalType.setType(sysTypeKey.getType());
            globalType.setNodePath(sysTypeKey.getTypeId() + ".");
            list.add(0, globalType);
        }
        if(TREE_TYPE_LAYUI.equals(treeType)){
            return processList(list);
        }
        return list;
    }
    /**
     * 根据catkey获取数据。
     * @param catKey
     * @return
     */
    public List<GlobalType> getByCatKey(String catKey,boolean hasRoot){

        String tenantId = ContextUtil.getCurrentUserTenantId();

        List<GlobalType> list= globalTypeDao.getByCatKey(catKey,tenantId,null);

        //是否有根节点。
        if(hasRoot){
            SysTypeKey  sysTypeKey=sysTypeKeyDao.getByKey(catKey);
            GlobalType globalType=new GlobalType();
            globalType.setTypeName(sysTypeKey.getTypeName());
            globalType.setCatKey(sysTypeKey.getTypeKey());
            globalType.setParentId("0");
            globalType.setIsParent("true");
            globalType.setTypeId(sysTypeKey.getTypeId());
            globalType.setType(sysTypeKey.getType());
            globalType.setNodePath(sysTypeKey.getTypeId() +".");
            list.add(0, globalType);
        }
        return list;
    }
    /**
     * 根据catkey获取数据。
     * @param queryFilter
     * @return
     */
    public List<GlobalType> getByCatKey(QueryFilter queryFilter) {
        return globalTypeDao.getByCatKeyQueryFilter(queryFilter);
    }

    /**
     * 组装成layui需要的树形结构
     * @param list 分类集合
     * @return 分类树
     */
    private List<GlobalType> processList(List<GlobalType> list) {
        return getChildList(list);
    }

    /**
     * 获取子分类集合
     * @param parentId 父节点ID
     * @return 子分类集合
     */
    public List<GlobalType> getChildren(String parentId){
        List<GlobalType> children = globalTypeDao.getGlobalTypeByParentId(parentId);
        return getChildList(children);
    }

    /**
     * 获取子分类集合
     * @param list 分类集合
     * @return 子分类集合
     */
    private List<GlobalType> getChildList(List<GlobalType> list){
        List retList = new ArrayList<>();
        for (GlobalType typeInfo : list) {
            Map map = new HashMap();
            map.put("title", typeInfo.getTypeName());
            map.put("id", typeInfo.getNodeKey());
            map.put("categoryId", typeInfo.getTypeId());
            map.put("children", getChildren(typeInfo.getTypeId()));
            map.put("spread",true);
            retList.add(map);
        }
        return retList;
    }


    /**
     * 取得初始分类类型。
     *
     * @param isRoot   是否根节点。
     * @param parentId 父节点。
     * @return GlobalType
     * @throws Exception 异常
     */
    public GlobalType getInitGlobalType(int isRoot, String parentId) throws Exception {
        GlobalType globalType = new GlobalType();
        String typeId = UUIDUtils.getUUIDFor32();
        //如果是根节点，则从SysTypeKey获取数据构建分类类型
        if (isRoot == 1) {
            SysTypeKey sysTypeKey = sysTypeKeyDao.getById(parentId);
            globalType.setCatKey(sysTypeKey.getTypeKey());
            globalType.setTypeName(sysTypeKey.getTypeName());
            globalType.setParentId(parentId);
            globalType.setNodePath(parentId + "." + typeId + ".");
            globalType.setType(sysTypeKey.getType());
        } else {
            //获取父类构建分类类型。
            globalType = globalTypeDao.getById(parentId);
            String nodePath = globalType.getNodePath();
            globalType.setNodePath(nodePath + typeId + ".");
        }
        globalType.setTypeId(typeId);
        return globalType;
    }

    /**
     * 对象功能：判断是否存在该节点key的记录
     *
     * @param catKey  分类key
     * @param nodeKey 节点key
     */
    public boolean isNodeKeyExists(String catKey, String nodeKey) {
        int i = globalTypeDao.isNodeKeyExists(catKey, nodeKey);
        return i > 0;
    }

    /**
     * 对象功能：判断是否存在该节点名称记录
     *
     * @param catKey   分类key
     * @param nodeName 节点名称
     */
    public boolean isNodeNameExists(String catKey, String nodeName) {
        int i = globalTypeDao.isNodeNameExists(catKey, nodeName);
        return i > 0;
    }

    /**
     * 对象功能：修改判断该节点key名称是否重复
     *
     * @param typeId  id
     * @param catKey  分类key
     * @param nodeKey 节点key
     */
    public boolean isNodeKeyExistsForUpdate(String typeId, String catKey, String nodeKey) {
        int i = globalTypeDao.isNodeKeyExistsForUpdate(typeId, catKey, nodeKey);
        return i > 0;
    }

    /**
     * 根据类型Id删除类型，删除数据字典。
     * @param typeId
     */
    @Transactional(rollbackFor = Exception.class)
    public int delByTypeId(String typeId) {
        if(BeanUtils.isEmpty(typeId)){
            return 0;
        }
        GlobalType gt=globalTypeDao.getById(typeId);
        //留下路径
        String oldNodePath=gt.getNodePath();
        //取得下级的所有节点
        List<GlobalType> childrenList= globalTypeDao.getByNodePath(oldNodePath+"%");
        int i=0;
        for(GlobalType globalType:childrenList){
            String Id=globalType.getTypeId();
            int j = globalTypeDao.delById(Id);
            i = i+j;
        }
        return i;
    }

    /**
     * 根据catKey获取分类的xml数据
     * @param catKey
     * @param treeType
     * @return
     */
    public String getXmlByCatKey(String catKey, String treeType) {
        String tenantId = ContextUtil.getCurrentUserTenantId();
        List<GlobalType> list = globalTypeDao.getByCatKey(catKey,tenantId,treeType);
        SysTypeKey sysTypeKey = sysTypeKeyDao.getSysTypeKeyByKey(catKey);
        String typeId = sysTypeKey.getTypeId();

        StringBuffer sb = new StringBuffer("<folder id='0' label='全部'>");
        if(BeanUtils.isNotEmpty(list)){
            for(GlobalType globalType:list){
                if( !typeId.equals(globalType.getParentId()) ){
                    continue;
                }
                //TODO 后端代码不能拼前端的标签
                sb.append("<folder id='" + globalType.getTypeId() + "' label='" + globalType.getTypeName() + "'>");
                sb.append(getBmpChildList(list,globalType.getTypeId()));
                sb.append("</folder>");
            }
        }
        sb.append("</folder>");
        return sb.toString();
    }

    /**
     * 递归调用获取XML
     * @param list
     * @param typeId
     * @return
     */
    private String getBmpChildList(List<GlobalType> list, String typeId) {
        StringBuffer sb = new StringBuffer("");
        if(BeanUtils.isNotEmpty(list)){
            for(GlobalType globalType :list){
                if(globalType.getParentId().equals(typeId)){
                    //TODO 后端代码不能拼前端的标签
                    sb.append("<folder id='" + globalType.getTypeId() + "' label='" + globalType.getTypeName() + "'>");
                    sb.append(getBmpChildList(list,globalType.getTypeId()));
                    sb.append("</folder>");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 根据nodekey获取字典的分类类型
     * @param nodeKey 分类表的nodekey
     * @return GlobalType
     */
    //todo 多余方法确定不会用到后删除
    public GlobalType getByDictNodeKey(String nodeKey){
        if(StringUtil.isEmpty(nodeKey)){
            return null;
        }
        return globalTypeDao.getByDictNodeKey(nodeKey);
    }

    /**
     * 根据用户id取得类型列表。
     * @param catKey	分类ID
     * @param userId	用户ID
     * @param hasRoot	是否添加根节点
     * @return
     */
    public List<GlobalType> queryPersonType(String catKey, String userId, boolean hasRoot) {
        String tenantId = ContextUtil.getCurrentUserTenantId();
        List<GlobalType> list= globalTypeDao.queryPersonType( catKey,userId,tenantId);
        //是否有根节点。
        //TODO 这一段代码与getByCatKey方法中的代码几乎一样，抽取公共方法
        if(hasRoot){
            SysTypeKey  sysTypeKey=sysTypeKeyDao.getByKey(catKey);
            GlobalType globalType=new GlobalType();
            globalType.setTypeName(sysTypeKey.getTypeName());
            globalType.setCatKey(sysTypeKey.getTypeKey());
//TODO            globalType.setParentId(0L);//父节点
            globalType.setIsParent("true");
            globalType.setTypeId(sysTypeKey.getTypeId());
            globalType.setType(sysTypeKey.getType());
            globalType.setNodePath(sysTypeKey.getTypeId() +".");
            list.add(0, globalType);
        }
        return list;
    }
}
